<template>
  <div class="app-container">
    <el-tabs type="border-card">
    <el-form :inline="true" :model="searchParam" class="demo-form-inline head-form">
      <el-form-item label="兑换码">
        <el-input clearable v-model="searchParam.name" size="small" placeholder="请输入兑换码" />
      </el-form-item>
      <el-form-item label="兑换状态">
        <el-select v-model="searchParam.status" placeholder="请选择" size="small" width='100' >
          <el-option v-for="item in statusList" :key="item.status" :label="item.name" :value="item.status">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button :loading="tableLoading" @click="search" size="small" icon="el-icon-search" type="primary">搜索
        </el-button>
        <!--
        <el-button @click="memberInfo()" size="small" icon="el-icon-plus" type="primary">添加会员
        </el-button>
        <el-button icon="el-icon-date" @click="batchDel()" size="small" class="add">批量删除</el-button> -->
        <!-- <el-button icon="el-icon-setting" @click="batchCache()" size="small" class="add">重置缓存</el-button> -->
        <el-button @click="initSearchParam();search()" icon="el-icon-refresh-right" type="primary" size="small" style="background-color: #fff; border: 1px solid #ccc ; color: #666">清空
        </el-button>
        <el-button
            type="warning"
            icon="el-icon-download"
            size="small"
            @click="exportExcel()"
          >导出</el-button>

      </el-form-item>

    </el-form>
      <el-table stripe ref="table" :height="tableHeight" v-loading="tableLoading" :data="memberList" border row-key="id"
        @selection-change="handleSelectionChange">
        <el-table-column show-overflow-tooltip type="selection" align="center" />
        <!-- <el-table-column show-overflow-tooltip prop="id" label="ID" align="center" width="80" /> -->
        <el-table-column show-overflow-tooltip prop="code" label="兑换码" align="center" />
        <el-table-column show-overflow-tooltip prop="status" label="兑换状态" align="center"  >
          <template slot-scope="{row}">
            <div>
              <el-tag v-if="row.status == 0" type="warning" size="small">未兑换</el-tag>
              <el-tag v-if="row.status == 1" type="success" size="small">已兑换</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="userName" label="兑换人" align="center"  >
            <template slot-scope="{row}">
              <div v-if="row.userName" class="ku_name" @click="getOrderInfo(row.orderId)" >
                        {{row.userName}}
              </div>
              <div  v-else>
                      --
              </div>
            </template>
        </el-table-column>

      </el-table>
      <!-- 分页 -->
      <div class="page-current">
        <el-pagination background :current-page="currentPage" :page-size="pageSize" prev-text="上一页" next-text="下一页"
          layout="total, prev, pager, next, jumper" style="display: inline-block;" :total="count" @current-change="handlePageChange" />
      </div>
    </el-tabs>

    <!-- 编辑表单 -->
   <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" center :visible.sync="addDialogVisible" :title="dialogTitle+'渠道'">
      <editForm ref="editForm" :infoForm="infoForm"  style="width: 100%" @submit="submit" @closeWin="closeWin"></editForm>
    </el-dialog>

    <!-- 编辑表单 -->
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" center :visible.sync="orderShow" title="订单详情">
        <div class="orderBox">
          <el-form>
            <el-form-item label="用户头像 :">
                   <el-avatar :size="80" :src="orderInfo.userImg">
                     <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
                   </el-avatar>
            </el-form-item>
            <el-form-item label="用户名称 :">
                   {{orderInfo.userName}}
            </el-form-item>
            <el-form-item label="兑换课程 :">
                   {{orderInfo.productName}}
            </el-form-item>
            <el-form-item label="支付金额 :">
                   {{orderInfo.payAmount/100}}
            </el-form-item>
            <el-form-item label="支付时间 :">
                   {{orderInfo.payTime}}
            </el-form-item>
            <el-form-item label="订单号 :">
                   {{orderInfo.orderNo}}
            </el-form-item>
           </el-form>
        </div>
     </el-dialog>

  </div>
</template>
<script>
  import gzhApi from '@/api/gzh/code'
  import editForm from './edit'

  export default {
    name: "member",
    data() {
      return {
        statusList:[
          {
            name:'全部',
            status:''
          },
          {
            name:'未兑换',
            status:0
          },
          {
            name:'已兑换',
            status:1
          }

        ],
        orderShow:false,
        orderInfo:{

        },
        tableLoading: false,
        // 当前页
        currentPage: 1,
        // 总条数
        count: 0,
        // 每页条数
        pageSize: 10,
        // 显示编辑角色弹框
        addBtnLoading: false,
        addDialogVisible: false,
        delBtnLoading: false,
        channelList: [],
        searchParam: {
          name: '',
          status: ''
        },
        status: [{
          value: 1,
          label: '正常'
        }, {
          value: 2,
          label: '禁用'
        }],
        memberList: [],
        deviceList: [],
        infoForm: {
          name: '',
          status: 1,
          device: 5,
          source: 2,
        },
        loading: false,
        tableHeight: document.body.clientHeight - 245,
        btnFunc: [],
        isAdmin: false,
        dialogTitle: "添加",
      }
    },
    components: {
      editForm
    },
    created() {
      const {
        btnFunc,
        isAdmin
      } = this.$store.state.user;
      console.log(this.$store.state.user)
      this.btnFunc = btnFunc
      this.isAdmin = isAdmin
      this.pageSize = parseInt((document.body.clientHeight - 344) / 50)
    },
    mounted() {

      // 开启加载动画
      this.tableLoading = true
      // 获取数据列表
      this.getMemberList()

      // 获取渠道参数
      // this.getChannelList()
    },
    watch: {},
    methods: {
      // 导出Excel
      exportExcel(){
        var self_=this;
        this.$confirm('是否确认导出所有码库数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return gzhApi.exportExcel({
            id:localStorage.getItem('mId'),
            status:self_.searchParam.status
          });
        }).then(response => {
          console.log(this)
          this.download(response.msg);
        }).catch(function() {});
      },
      getOrderInfo(id){
        this.tableLoading=true
        gzhApi.orderInfo({id:id}).then(res => {
            console.log(res);
            if(res.code==200){
              this.orderInfo=res.data
              this.orderShow=true
            }
            this.tableLoading=false
        }).catch(e => {
        })

      },
       handleClick(tab, event) {
              console.log(tab, event);
      },
      // 获取编辑数据
      courseInfo(data){
        // 初始化表单
        this.initInfoForm()

        // 设置标题
        if (data == null) {
          this.dialogTitle = "添加";
          this.addDialogVisible=true
        } else {
        this.dialogTitle = "编辑";
        }
        this.$nextTick(function () {
          try {
            console.log(1111);
            this.tableLoading=true;
            gzhApi.courseInfo({id: data.id}).then(res => {
              this.tableLoading=false;
              this.infoForm = res.data
              console.log( this.infoForm)
               // 显示弹窗
               this.addDialogVisible=true
              this.$refs.editForm.$refs['infoForm'].resetFields()

            }).catch(e => {
            })
          } catch (e) {

          }
        })
      },

      handleSelectionChange(row) {
        console.log(row)
      },
      batchDel() {
        console.log(this.$refs.table.clearSelection());
      },
      // 异步获取数据
      async queryData() {
        // 获取设备类型
        await this.getParamList()
      },
      // 初始化搜索条件
      initSearchParam() {
        this.searchParam = {
          name: '',
          status: ''
        }
      },
      getChannelList() {
        var that = this;
        gzhApi.talkchannel({
          pageIndex: 1,
          pageSize: 1000
        }).then(res => {

          console.log('渠道=', res)
          if (res.code == 200) {
            that.channelList = res.data.records
          }

        }).catch(e => {

        })
      },
      // 获取数据列表
      getMemberList() {
        let searchParam = JSON.parse(JSON.stringify(this.searchParam))
        searchParam.pageIndex = this.currentPage
        searchParam.pageSize = this.pageSize
        searchParam.id=localStorage.getItem('mId')
        console.log(searchParam)
        gzhApi.courseCodeAll(searchParam).then(res => {
          this.memberList = res.data.records
          this.count = res.data.total
          this.tableLoading = false
        }).catch(e => {
          this.memberList = []
          this.tableLoading = false
        })
      },
      // 初始化表单
      initInfoForm() {
        this.infoForm = {
        coverUrl:'',
        courseName:'',
        salePrice:'',
        linePrice:'',
        courseDescribe:'',
        content:'',
        salePriced:'',
        linePriced:''
        }
      },
      // 删除记录
      memberDel(data) {
        this.$confirm('您确定要删该课程？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.delBtnLoading = true
          gzhApi.courseDel({
            id: data.id
          }).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功！'
            })
            this.delBtnLoading = false
            this.tableLoading = true
            this.getMemberList()
          }).catch(e => {
            this.delBtnLoading = false
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      // 获取参数
      getParamList() {
        gzhApi.getParamList().then(res => {
          const {
            device_list
          } = res.data
          this.deviceList = device_list ? device_list : {}
        }).catch(e => {
          this.deviceList = {}
        })
      },
      // 设置状态
      setStatus(data) {
        console.log(data)
        var content = ''
        if (data.status === 1) {
          content = '确定要启用吗？'
        } else {
          content = '确定要禁用吗？'
        }
        this.$confirm(content, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = {
            status: data.status,
            id: data.id
          }
          this.tableLoading = true
          gzhApi.courseEdit(params).then(res => {
            this.$message({
              type: 'success',
              message: '操作成功！'
            })
            this.getMemberList()
          }).catch(e => {
            let memberList = JSON.parse(JSON.stringify(this.memberList))
            for (let i = 0; i < memberList.length; i++) {
              if (memberList[i].id == data.id) {
                memberList[i].status = data.status == 1 ? 0 : 1
              }
            }
            this.memberList = Object.assign([], memberList)
            this.tableLoading = false
          })
        }).catch(() => {
          let memberList = JSON.parse(JSON.stringify(this.memberList))
          for (let i = 0; i < memberList.length; i++) {
            if (memberList[i].id == data.id) {
              memberList[i].status = data.status == 1 ? 0 : 1
            }
          }
          this.memberList = Object.assign([], memberList)
          this.$message({
            type: 'info',
            message: '已取消该操作！'
          })
        });
      },
      handlePageChange(val) {
        this.currentPage = val
        this.tableLoading = true
        this.$refs.table.bodyWrapper.scrollTop = 0;
        this.getMemberList()
      },
      // 搜索
      search() {
        this.currentPage = 1
        this.tableLoading = true
        this.$refs.table.bodyWrapper.scrollTop = 0;
        this.getMemberList()
      },
      // 提交表单后逻辑处理
      submit(type) {
        if (type == 0) {
          // 添加
          this.search()
        } else {
          // 编辑
          this.tableLoading = true
          this.getMemberList()
          this.$refs.table.bodyWrapper.scrollTop = 0;
          this.addDialogVisible = false
        }
      },
      // 关闭窗体
      closeWin() {
        console.log("关闭")
        // 调用初始化表单方法
        this.initInfoForm()
        // 设置弹窗不可见
        this.addDialogVisible = false
      }
    }
  }
</script>

<style lang="less">
  .app-container {
    width: 100%;

    .page-current {
      text-align: center;
      padding: 15px 5px;
      padding-bottom: 0px;

      .sure-page-btn {
        display: inline-block;
        height: 28px;
        line-height: 0;
        width: 46px;
        padding: 0;
        vertical-align: top;
      }
    }

    .ku_name:hover{
      text-decoration: underline;
      cursor: pointer;
    }
    .ku_name{
      color:#409EFF ;
    }
    .bannerImg img{
      width: 100%;
    }
    .orderBox{
        .el-form-item{
          margin-bottom: 0;
          display: flex;
              align-items: center;
        }
        .el-form-item__label{
              width: 100px;
              text-align: left;
        }
        .el-form-item__content{
          color: #1890ff;
        }
    }


  }

</style>
